package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomerException;
import com.itheima.reggie.mappers.CategoryMapper;
import com.itheima.reggie.mappers.DishMapper;
import com.itheima.reggie.mappers.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Override
    public void save(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.save(category);
    }

    @Override
    public R<Page<Category>> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Category> list = categoryMapper.findAll();

        PageInfo<Category> pageInfo = new PageInfo<>(list);

        Page<Category> resultPage = new Page<>(pageInfo.getList(), pageInfo.getTotal(), page, pageSize);

        return R.success(resultPage);
    }

    @Override
    public void delete(Long id) {
        Integer count = dishMapper.selectByCategoryId(id);
        if (count > 0) {
            throw new CustomerException("该类别已经被其他菜品关联，不能删除");
        }

        count = setmealMapper.selectByCategoryId(id);

        if (count > 0) {
            throw new CustomerException("该类别已经被其他套餐关联，不能删除");
        }

        categoryMapper.delete(id);
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());

        categoryMapper.update(category);
    }

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override
    public R<List<Category>> list(Integer type) {
        List<Category> categoryList = categoryMapper.list(type);
        return R.success(categoryList);
    }

}
